package com.example.kuaizu.utils;

import java.io.*;
import java.util.Base64;

public class SerializerUtils {
    /**
     * 将字符串数组序列化为字节数组
     *
     * @param array 要序列化的字符串数组
     * @return 序列化后的字节数组
     */
    public static byte[] serializeArray(String[] array) throws IOException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(array);
            return bos.toByteArray();
        }
    }



    /**
     * 将对象序列化为 Base64 字符串
     * @param obj 要序列化的对象
     * @return Base64 编码的字符串
     */
    public static String serializeToBase64(Object obj) throws IOException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(obj);
            byte[] bytes = bos.toByteArray();
            return Base64.getEncoder().encodeToString(bytes);
        }
    }

    /**
     * 将 Base64 字符串反序列化为对象
     * @param base64Str Base64 编码的字符串
     * @return 反序列化后的对象
     */
    public static Object deserializeFromBase64(String base64Str) throws IOException, ClassNotFoundException {
        byte[] bytes = Base64.getDecoder().decode(base64Str);
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bis)) {
            return ois.readObject();
        }
    }
    /**
     * 将字节数组反序列化为字符串数组
     *
     * @param bytes 要反序列化的字节数组
     * @return 反序列化后的字符串数组
     */
    public static String[] deserializeArray(byte[] bytes) throws IOException, ClassNotFoundException {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bis)) {
            return (String[]) ois.readObject();
        }
    }
}